package service

import (
	"context"
	pb "medicine/api/medicine/v1"
	"medicine/internal/biz"
)

// BrandService 品牌服务实现，处理品牌相关的 gRPC 请求
// 调用 usecase 层实现具体业务逻辑
type BrandService struct {
	pb.UnimplementedBrandServer                   // gRPC 品牌服务基类
	uc                          *biz.BrandUsecase // 品牌用例层依赖
}

// NewBrandService 创建品牌服务实例
func NewBrandService(uc *biz.BrandUsecase) *BrandService {
	return &BrandService{uc: uc}
}

// CreateBrand 创建品牌
func (s *BrandService) CreateBrand(ctx context.Context, req *pb.CreateBrandRequest) (*pb.BrandReply, error) {
	b := &biz.Brand{
		Name: req.Name,
	}
	newB, err := s.uc.Create(ctx, b)
	if err != nil {
		return nil, err
	}
	return &pb.BrandReply{
		Id:   newB.ID,
		Name: newB.Name,
	}, nil
}

// GetBrand 获取品牌详情
func (s *BrandService) GetBrand(ctx context.Context, req *pb.GetBrandRequest) (*pb.BrandReply, error) {
	b, err := s.uc.Get(ctx, req.Id)
	if err != nil {
		return nil, err
	}
	return &pb.BrandReply{
		Id:   b.ID,
		Name: b.Name,
	}, nil
}

// UpdateBrand 更新品牌
func (s *BrandService) UpdateBrand(ctx context.Context, req *pb.UpdateBrandRequest) (*pb.BrandReply, error) {
	b := &biz.Brand{
		ID:   req.Id,
		Name: req.Name,
	}
	newB, err := s.uc.Update(ctx, b)
	if err != nil {
		return nil, err
	}
	return &pb.BrandReply{
		Id:   newB.ID,
		Name: newB.Name,
	}, nil
}

// DeleteBrand 删除品牌
func (s *BrandService) DeleteBrand(ctx context.Context, req *pb.DeleteBrandRequest) (*pb.DeleteBrandReply, error) {
	err := s.uc.Delete(ctx, req.Id)
	return &pb.DeleteBrandReply{Success: err == nil}, err
}

// ListBrand 分页获取品牌列表
func (s *BrandService) ListBrand(ctx context.Context, req *pb.ListBrandRequest) (*pb.ListBrandReply, error) {
	brands, total, err := s.uc.List(ctx, int(req.Page), int(req.PageSize))
	if err != nil {
		return nil, err
	}
	var replies []*pb.BrandReply
	for _, b := range brands {
		replies = append(replies, &pb.BrandReply{
			Id:   b.ID,
			Name: b.Name,
		})
	}
	return &pb.ListBrandReply{Brands: replies, Total: int32(total)}, nil
}
